﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CoreVirtuoso.Descriptions;
using Infrastructure.Lgd.Interfaces;
using NGenerics.DataStructures;
using VirtuosoDal.Repositories.RdfRepositories.Interfaces.Lgd;
using WebGuiMvc.Helpers;

namespace AspNetMvc.Controllers
{
   public partial class LgdController : BaseController
   {
      private readonly ILgdContentRepository _lgdContentRepository;
      private readonly ILgdTreeFilteringService _lgdTreeFilteringService;

      public LgdController(ILgdContentRepository lgdContentRepository,
         ILgdTreeFilteringService lgdTreeFilteringService)
      {
         _lgdContentRepository = lgdContentRepository;
         _lgdTreeFilteringService = lgdTreeFilteringService;
      }

      [Authorize]
      [AcceptVerbs(HttpVerbs.Post)]
      public virtual JsonResult GetNearObjectsTypes(string westLatitude, string southLongitude,
         string eastLatitude, string northLongitude)
      {
         //ToDo: check for maliciuos latitude/longitude using differnece

         //We can't use double parameters, because they will be parsed using current culture (in this case delimeter is undetermined)
         double doubleWestLatitude = Double.Parse(westLatitude, CultureInfo.InvariantCulture);
         double doubleSouthLongitude = Double.Parse(southLongitude, CultureInfo.InvariantCulture);
         double doubleEastLatitude = Double.Parse(eastLatitude, CultureInfo.InvariantCulture);
         double doubleNorthLongitude = Double.Parse(northLongitude, CultureInfo.InvariantCulture);

         List<string> nearestObjectsTypes = _lgdContentRepository.GetNearestObjectsTypes(doubleWestLatitude, doubleSouthLongitude,
            doubleEastLatitude, doubleNorthLongitude);

         if (nearestObjectsTypes.Count == 0)
            return Json(nearestObjectsTypes);

         IList<GeneralTree<EntityDescription>> categories = _lgdTreeFilteringService.GetCategoriesTree(nearestObjectsTypes);

         List<EntityDescription> categoriesHierarchyAsList = HierarchyHelper.GetHierarchyAsList(categories);

         return Json(categoriesHierarchyAsList);
      }

   }
}
